package com.luyou.units;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * 工具类
 */
public final class FileUtils {

    /**
     * 通过路径获取需要加载的class类
     * @param rootPath 文件夹跟路径
     * @param extName 文件后缀名 比如class
     * @return 返回文件列表
     */
    public static List<File> findLoadClassFile(String rootPath, String extName){
        File rootFile = new File(rootPath);
        try ( DirectoryStream<Path> paths = Files.newDirectoryStream(rootFile.toPath());) {
            List<File> fileList = new ArrayList<>();
            for (Path path : paths) {
                if(path.toFile().isDirectory()){
                    List<File> sonFiles = findLoadClassFile(path.toString(), extName);
                    if(sonFiles != null && sonFiles.size() >0){
                        fileList.addAll(sonFiles);
                    }
                }else {
                    if(extName == null || "".equals(extName) || "*".equals(extName) || path.getFileName().toString().endsWith(extName)){
                        File file = path.toFile();
                        fileList.add(file);
                    }
                }
            }
            return fileList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
